import React from "react";
import { Form, Switch } from "antd";
import { genWidget } from "../core";
import ItemLayout, { WrapProps } from "./formLabel";

export const genSwitchWidget = (c: WidgetCategory): SwitchWidget => {
  const base = genWidget(c);
  return {
    ...base,
    label: "逻辑选择",
    placeholder: "请选择",
    checkedValue: "1",
    unCheckedValue: "0",
  };
};

const SwitchWidgetRender = (props: WrapProps<SwitchWidget>) => {
  const {
    isview,
    name = "",
    unCheckedValue,
    checkedValue,
    isRequired,
    placeholder,
  } = props;
  return (
    <ItemLayout {...props}>
      {!isview && <Switch id={props.uuid}></Switch>}
      {isview && (
        <Form.Item
          required={props.isRequired}
          rules={[
            {
              required: isRequired,
              message: placeholder,
            },
          ]}
          shouldUpdate
        >
          {({ setFieldsValue, getFieldValue }) => {
            const value = getFieldValue(name);
            return (
              <Form.Item noStyle name={name}>
                <Switch
                  id={props.uuid}
                  checked={value === checkedValue}
                  onChange={(e) => {
                    if (e) {
                      setFieldsValue({ [name]: checkedValue });
                    } else {
                      setFieldsValue({ [name]: unCheckedValue });
                    }
                  }}
                ></Switch>
              </Form.Item>
            );
          }}
        </Form.Item>
      )}
    </ItemLayout>
  );
};

export default SwitchWidgetRender;
